// 1. React核心库
import React, { useState, useRef } from 'react';

// 2. UI组件库 - 按字母顺序排列
import {
  Button,
  Tag,
  Space,
  message,
  Tooltip,
  Typography,
  Modal,
  Descriptions,
  Input,
  Form,
  Tabs,
  Transfer,
} from 'antd';
import type { TransferProps } from 'antd';

// 3. 图标库
import {
  TeamOutlined,
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  EyeOutlined,
  UserOutlined,
  KeyOutlined,
  ReloadOutlined,
  SettingOutlined,
  SaveOutlined,
  CloseOutlined,
} from '@ant-design/icons';

// 4. 专业组件库
import { PageContainer, ProTable, ProList, ProForm, ProFormText } from '@ant-design/pro-components';
import type { ProColumns, ActionType } from '@ant-design/pro-components';

// 5. 工具库
import { history, useAccess } from '@umijs/max';

// 6. 项目内部模块
import { apiClients } from '@/services/apiClient';
import { autoLoginInDev } from '@/utils/autoLogin';

// 7. 生成的类型定义 (必须使用，禁止手工定义)
import type { 
  GroupList, 
  PaginatedGroupListList,
  GroupDetail,
  UserList,
  PermissionList
} from '@/services/generated/src/index';

// 解构常用子组件
const { Text, Title } = Typography;

const GroupsNew: React.FC = () => {
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [deleteLoading, setDeleteLoading] = useState(false);
  const [detailVisible, setDetailVisible] = useState(false);
  const [selectedGroup, setSelectedGroup] = useState<GroupDetail | null>(null);
  const [usersVisible, setUsersVisible] = useState(false);
  const [permissionsVisible, setPermissionsVisible] = useState(false);
  const [editVisible, setEditVisible] = useState(false);
  const [editingGroup, setEditingGroup] = useState<GroupList | null>(null);
  const [editForm, setEditForm] = useState<{ name: string; description?: string }>({ name: '' });
  const [editLoading, setEditLoading] = useState(false);
  const [activeTab, setActiveTab] = useState('basic');

  // Transfer相关状态
  const [allUsers, setAllUsers] = useState<any[]>([]);
  const [allPermissions, setAllPermissions] = useState<any[]>([]);
  const [selectedUsers, setSelectedUsers] = useState<number[]>([]);
  const [selectedPermissions, setSelectedPermissions] = useState<number[]>([]);
  const [transferLoading, setTransferLoading] = useState(false);

  // 创建相关状态
  const [createVisible, setCreateVisible] = useState(false);
  const [createLoading, setCreateLoading] = useState(false);
  const [createForm] = Form.useForm();

  const actionRef = useRef<ActionType>();
  const access = useAccess();

  // ➕ 创建组
  const handleCreateGroup = async (values: any) => {
    try {
      setCreateLoading(true);
      await apiClients.permissions.permissionsGroupsCreate({
        createGroupRequest: {
          name: values.name,
          display_name: values.display_name,
          description: values.description || '',
          is_system: false
        }
      });

      message.success('组创建成功');
      setCreateVisible(false);
      createForm.resetFields();
      actionRef.current?.reload();
    } catch (error: any) {
      const errorMessage = error?.response?.data?.message || error?.message || '创建失败';
      message.error(errorMessage);
    } finally {
      setCreateLoading(false);
    }
  };

  // 📋 加载编辑数据
  const loadEditData = async (groupId: number) => {
    try {
      setTransferLoading(true);

      // 并行加载所有数据
      const [groupResponse, usersResponse, permissionsResponse, groupUsersResponse, groupPermissionsResponse] = await Promise.all([
        apiClients.permissions.permissionsGroupsRetrieve({ id: groupId }),
        apiClients.users.usersList({ pageSize: 1000 }), // 获取所有用户
        apiClients.permissions.permissionsPermissionsList({ pageSize: 1000 }), // 获取所有权限
        apiClients.permissions.permissionsGroupsUsersList({ id: groupId, pageSize: 1000 }),
        apiClients.permissions.permissionsGroupsPermissionsList({ id: groupId, pageSize: 1000 })
      ]);

      // 处理响应数据
      const groupData = (groupResponse as any).data || groupResponse;
      const allUsersData = ((usersResponse as any).data || usersResponse).items || [];
      const allPermissionsData = ((permissionsResponse as any).data || permissionsResponse).items || [];
      const groupUsersData = ((groupUsersResponse as any).data || groupUsersResponse).items || [];
      const groupPermissionsData = ((groupPermissionsResponse as any).data || groupPermissionsResponse).items || [];

      console.log('🔍 编辑数据加载结果:', {
        groupData,
        allUsersCount: allUsersData.length,
        allPermissionsCount: allPermissionsData.length,
        groupUsersCount: groupUsersData.length,
        groupPermissionsCount: groupPermissionsData.length,
        groupPermissions: groupData.permissions,
        allPermissionIds: allPermissionsData.map((p: any) => p.id),
        groupPermissionIds: groupData.permissions
      });

      // 验证权限ID匹配
      const validPermissionIds = groupData.permissions?.filter((id: number) =>
        allPermissionsData.some((p: any) => p.id === id)
      ) || [];

      console.log('🎯 有效权限ID:', validPermissionIds);
      console.log('🎯 无效权限ID:', groupData.permissions?.filter((id: number) =>
        !allPermissionsData.some((p: any) => p.id === id)
      ) || []);

      // 设置数据
      setAllUsers(allUsersData);
      setAllPermissions(allPermissionsData);

      // 🔑 关键修复：从权限对象数组中提取ID
      const permissionIds = Array.isArray(groupData.permissions)
        ? groupData.permissions.map((permission: any) => permission.id).filter((id: any) => typeof id === 'number')
        : [];

      console.log('🎯 组权限对象数组:', groupData.permissions);
      console.log('🎯 提取的权限ID数组:', permissionIds);
      setSelectedPermissions(permissionIds);

      // 🔑 关键修复：使用组用户列表中的用户ID作为已选用户
      const userIds = groupUsersData.map((user: any) => user.id);
      console.log('🎯 设置用户ID数组:', userIds);
      setSelectedUsers(userIds);

      return groupData;
    } catch (error: any) {
      message.error('加载编辑数据失败');
      throw error;
    } finally {
      setTransferLoading(false);
    }
  };

  // ✏️ 开始编辑组
  const handleStartEdit = async (record: GroupList) => {
    if (!access.canUpdateGroup) {
      message.error('没有编辑组的权限');
      return;
    }

    try {
      setEditingGroup(record);
      setEditForm({
        name: record.name,
        description: record.description || ''
      });

      // 🔑 关键修复：先设置初始权限数据，避免显示(0)
      // 注意：这里使用表格中显示的权限数量作为占位符
      // 实际权限ID将在loadEditData中正确设置
      console.log('🎯 表格记录权限数量:', record.permission_count);
      // 暂时不设置selectedPermissions，等待loadEditData完成

      setEditVisible(true);
      setActiveTab('basic');

      // 异步加载完整编辑数据
      await loadEditData(record.id);
    } catch (error) {
      setEditVisible(false);
      setEditingGroup(null);
    }
  };

  // � 保存编辑
  const handleSaveEdit = async () => {
    if (!editingGroup) return;

    if (!editForm.name.trim()) {
      message.error('组名不能为空');
      return;
    }

    try {
      setEditLoading(true);

      // 1. 更新组基本信息
      await apiClients.permissions.permissionsGroupsUpdate({
        id: editingGroup.id,
        groupRequest: {
          name: editForm.name.trim(),
          permissions: selectedPermissions // 使用选中的权限
        }
      });

      // 2. 更新组用户 - 先获取当前组用户，然后计算差异
      const currentUsersResponse = await apiClients.permissions.permissionsGroupsUsersList({
        id: editingGroup.id,
        pageSize: 1000
      });
      const currentUsers = ((currentUsersResponse as any).data || currentUsersResponse).items || [];
      const currentUserIds = currentUsers.map((user: any) => user.id);

      // 计算需要添加和移除的用户
      const usersToAdd = selectedUsers.filter(id => !currentUserIds.includes(id));
      const usersToRemove = currentUserIds.filter((id: number) => !selectedUsers.includes(id));

      // 添加用户
      if (usersToAdd.length > 0) {
        await apiClients.permissions.permissionsGroupsAssignUsersCreate({
          id: editingGroup.id,
          assignGroupRequest: {
            user_ids: usersToAdd
          }
        });
      }

      // 移除用户
      if (usersToRemove.length > 0) {
        await apiClients.permissions.permissionsGroupsRemoveUsersCreate({
          id: editingGroup.id,
          removeUsersFromGroupRequest: {
            user_ids: usersToRemove
          }
        });
      }

      message.success('更新成功');
      setEditVisible(false);
      setEditingGroup(null);
      setEditForm({ name: '' });
      setActiveTab('basic');
      actionRef.current?.reload();
    } catch (error: any) {
      const errorMessage = error?.response?.data?.message || error?.message || '更新失败';
      message.error(errorMessage);
    } finally {
      setEditLoading(false);
    }
  };

  // ❌ 取消编辑
  const handleCancelEdit = () => {
    setEditVisible(false);
    setEditingGroup(null);
    setEditForm({ name: '' });
    setActiveTab('basic');
    setAllUsers([]);
    setAllPermissions([]);
    setSelectedUsers([]);
    setSelectedPermissions([]);
  };

  // �🗑️ 删除组
  const handleDelete = async (groupId: number, groupName: string) => {
    if (!access.canDeleteGroup) {
      message.error('没有删除组的权限');
      return;
    }

    Modal.confirm({
      title: '确认删除组',
      content: (
        <div>
          <p>确定要删除组 <strong>"{groupName}"</strong> 吗？</p>
          <p style={{ color: '#ff4d4f', fontSize: '12px' }}>
            ⚠️ 删除组不会删除组内用户，但会移除用户的组权限
          </p>
        </div>
      ),
      okText: '确定删除',
      okType: 'danger',
      cancelText: '取消',
      onOk: async () => {
        try {
          setDeleteLoading(true);
          await apiClients.permissions.permissionsGroupsDestroy({ id: groupId });
          message.success(`组 "${groupName}" 删除成功`);
          actionRef.current?.reload();
        } catch (error: any) {
          const errorMessage = error?.response?.data?.message || error?.message || '删除失败';
          message.error(errorMessage);
        } finally {
          setDeleteLoading(false);
        }
      }
    });
  };

  // 👁️ 查看组详情
  const handleViewDetail = async (groupId: number) => {
    try {
      const response = await apiClients.permissions.permissionsGroupsRetrieve({ id: groupId });
      const groupData = (response as any).data || response;
      setSelectedGroup(groupData);
      setDetailVisible(true);
    } catch (error: any) {
      message.error('获取组详情失败');
    }
  };

  // 👥 查看组用户
  const handleViewUsers = async (groupId: number) => {
    try {
      // 获取组详情
      const groupResponse = await apiClients.permissions.permissionsGroupsRetrieve({ id: groupId });
      const groupData = (groupResponse as any).data || groupResponse;

      // 获取组用户列表
      const usersResponse = await apiClients.permissions.permissionsGroupsUsersList({ id: groupId });
      const usersData = (usersResponse as any).data || usersResponse;

      setSelectedGroup({
        ...groupData,
        users: usersData.items || []
      });
      setUsersVisible(true);
    } catch (error: any) {
      message.error('获取组用户失败');
    }
  };

  // 🔑 查看组权限
  const handleViewPermissions = async (groupId: number) => {
    try {
      const response = await apiClients.permissions.permissionsGroupsRetrieve({ id: groupId });
      const groupData = (response as any).data || response;
      setSelectedGroup(groupData);
      setPermissionsVisible(true);
    } catch (error: any) {
      message.error('获取组权限失败');
    }
  };

  // 📋 表格列定义
  const columns: ProColumns<GroupList>[] = [
    {
      title: 'ID',
      dataIndex: 'id',
      width: 80,
      search: false,
      sorter: true,
    },
    {
      title: '组名',
      dataIndex: 'name',
      width: 200,
      copyable: true,
      ellipsis: true,
      render: (text, record) => (
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <span>{text}</span>
          {record.is_system && (
            <Tag color="red" style={{ fontSize: '11px', padding: '0 4px' }}>系统</Tag>
          )}
        </div>
      ),
    },
    {
      title: '用户数量',
      dataIndex: 'user_count',
      width: 100,
      search: false,
      render: (count) => (
        <Tag color="blue" icon={<UserOutlined />}>
          {count} 人
        </Tag>
      ),
    },
    {
      title: '权限数量',
      dataIndex: 'permission_count',
      width: 100,
      search: false,
      render: (count) => (
        <Tag color="green" icon={<KeyOutlined />}>
          {count} 项
        </Tag>
      ),
    },
    {
      title: '显示名称',
      dataIndex: 'display_name',
      width: 150,
      search: false,
      ellipsis: true,
    },
    {
      title: '描述',
      dataIndex: 'description',
      width: 200,
      search: false,
      ellipsis: true,
      render: (text) => (
        <Text ellipsis={{ tooltip: text }}>
          {text || '暂无描述'}
        </Text>
      ),
    },
    {
      title: '系统组',
      dataIndex: 'is_system',
      width: 100,
      search: false,
      render: (isSystem) => (
        <Tag color={isSystem ? 'red' : 'default'}>
          {isSystem ? '系统组' : '普通组'}
        </Tag>
      ),
    },
    {
      title: '操作',
      valueType: 'option',
      width: 200,
      render: (_, record) => [
        <Tooltip key="view" title="查看详情">
          <Button
            type="link"
            size="small"
            icon={<EyeOutlined />}
            onClick={() => handleViewDetail(record.id)}
          />
        </Tooltip>,
        
        <Tooltip key="users" title="查看用户">
          <Button
            type="link"
            size="small"
            icon={<UserOutlined />}
            onClick={() => handleViewUsers(record.id)}
          />
        </Tooltip>,

        <Tooltip key="permissions" title="查看权限">
          <Button
            type="link"
            size="small"
            icon={<KeyOutlined />}
            onClick={() => handleViewPermissions(record.id)}
          />
        </Tooltip>,

        access.canUpdateGroup && !record.is_system && (
          <Tooltip key="edit" title="编辑组">
            <Button
              type="link"
              size="small"
              icon={<EditOutlined />}
              onClick={() => handleStartEdit(record)}
            />
          </Tooltip>
        ),

        access.canDeleteGroup && !record.is_system && (
          <Tooltip key="delete" title="删除组">
            <Button
              type="link"
              size="small"
              danger
              loading={deleteLoading}
              icon={<DeleteOutlined />}
              onClick={() => handleDelete(record.id, record.name)}
            />
          </Tooltip>
        ),
      ].filter(Boolean),
    },
  ];

  return (
    <PageContainer
      header={{
        title: '组管理',
        breadcrumb: {
          items: [
            { title: '首页', path: '/' },
            { title: '权限管理', path: '/permissions' },
            { title: '组管理' },
          ],
        },
      }}
    >
      <ProTable<GroupList>
        columns={columns}
        actionRef={actionRef}
        request={async (params, sort) => {
          try {
            await autoLoginInDev(); // 开发环境自动登录

            // 处理排序参数
            let ordering = undefined;
            if (sort && Object.keys(sort).length > 0) {
              const sortField = Object.keys(sort)[0];
              const sortOrder = sort[sortField];
              ordering = sortOrder === 'ascend' ? sortField : `-${sortField}`;
            }

            const response = await apiClients.permissions.permissionsGroupsList({
              page: params.current || 1,
              pageSize: params.pageSize || 20,
              search: params.name,
              ordering,
            });

            console.log('🚀 组列表API响应:', response);

            // 🔑 关键：正确提取分页数据
            const responseData = (response as any).data || response;
            
            return {
              data: responseData.items || [],
              success: true,
              total: responseData.total || 0,
            };
          } catch (error: any) {
            console.error('❌ 获取组列表失败:', error);
            message.error('获取组列表失败');
            return {
              data: [],
              success: false,
              total: 0,
            };
          }
        }}
        rowKey="id"
        search={{
          labelWidth: 'auto',
          defaultCollapsed: false,
        }}
        pagination={{
          defaultPageSize: 20,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条/总共 ${total} 条`,
        }}
        toolBarRender={() => [
          access.canCreateGroup && (
            <Button
              key="create"
              type="primary"
              icon={<PlusOutlined />}
              onClick={() => setCreateVisible(true)}
            >
              新建组
            </Button>
          ),
          
          <Button
            key="refresh"
            icon={<ReloadOutlined />}
            onClick={() => actionRef.current?.reload()}
          >
            刷新
          </Button>,
        ].filter(Boolean)}
        options={{
          setting: {
            listsHeight: 400,
          },
        }}
        scroll={{ x: 1200 }}
      />

      {/* 组详情弹窗 */}
      <Modal
        title={`组详情 - ${selectedGroup?.name}`}
        open={detailVisible}
        onCancel={() => setDetailVisible(false)}
        footer={null}
        width={800}
      >
        {selectedGroup && (
          <Descriptions column={2} bordered>
            <Descriptions.Item label="组ID">{selectedGroup.id}</Descriptions.Item>
            <Descriptions.Item label="组名">{selectedGroup.name}</Descriptions.Item>
            <Descriptions.Item label="用户数量">
              <Tag color="blue" icon={<UserOutlined />}>
                {selectedGroup.user_count} 人
              </Tag>
            </Descriptions.Item>
            <Descriptions.Item label="权限数量">
              <Tag color="green" icon={<KeyOutlined />}>
                {selectedGroup.permission_count} 项
              </Tag>
            </Descriptions.Item>
            <Descriptions.Item label="权限列表" span={2}>
              <div>
                {selectedGroup.permissions.map((permission, index) => (
                  <Tag key={index} color="green" style={{ margin: 2 }}>
                    {permission.name}
                  </Tag>
                ))}
                {selectedGroup.permissions.length === 0 && (
                  <Text type="secondary">暂无权限</Text>
                )}
              </div>
            </Descriptions.Item>
          </Descriptions>
        )}
      </Modal>

      {/* 组用户弹窗 */}
      <Modal
        title={`组用户 - ${selectedGroup?.name}`}
        open={usersVisible}
        onCancel={() => setUsersVisible(false)}
        footer={null}
        width={600}
      >
        {selectedGroup && (
          <div>
            <Title level={5}>用户列表 ({selectedGroup.user_count} 人)</Title>
            <div style={{ marginTop: 16 }}>
              {(selectedGroup as any).users && (selectedGroup as any).users.length > 0 ? (
                (selectedGroup as any).users.map((user: any, index: number) => (
                  <Tag key={index} color="blue" style={{ margin: 4 }}>
                    <UserOutlined /> {user.username}
                  </Tag>
                ))
              ) : (
                <Text type="secondary">暂无用户</Text>
              )}
            </div>
          </div>
        )}
      </Modal>

      {/* 组权限弹窗 */}
      <Modal
        title={`组权限 - ${selectedGroup?.name}`}
        open={permissionsVisible}
        onCancel={() => setPermissionsVisible(false)}
        footer={null}
        width={800}
      >
        {selectedGroup && (
          <div>
            <Title level={5}>权限列表 ({selectedGroup.permission_count} 项)</Title>
            <div style={{ marginTop: 16 }}>
              {selectedGroup.permissions && selectedGroup.permissions.length > 0 ? (
                selectedGroup.permissions.map((permission, index) => (
                  <Tag key={index} color="green" style={{ margin: 4 }}>
                    <KeyOutlined /> {permission.name}
                  </Tag>
                ))
              ) : (
                <Text type="secondary">暂无权限</Text>
              )}
            </div>
          </div>
        )}
      </Modal>

      {/* 编辑组弹窗 */}
      <Modal
        title={`编辑组 - ${editingGroup?.name}`}
        open={editVisible}
        onCancel={handleCancelEdit}
        onOk={handleSaveEdit}
        confirmLoading={editLoading}
        okText="保存"
        cancelText="取消"
        width={900}
        style={{ top: 20 }}
      >
        <Tabs
          activeKey={activeTab}
          onChange={setActiveTab}
          items={[
            {
              key: 'basic',
              label: (
                <span>
                  <EditOutlined />
                  基本信息
                </span>
              ),
              children: (
                <Form layout="vertical" style={{ marginTop: 16 }}>
                  <Form.Item
                    label="组名"
                    required
                    help="组名不能为空"
                  >
                    <Input
                      value={editForm.name}
                      onChange={(e) => setEditForm({ ...editForm, name: e.target.value })}
                      placeholder="请输入组名"
                      maxLength={150}
                      showCount
                    />
                  </Form.Item>

                  <Form.Item
                    label="描述"
                    help="可选，描述组的用途"
                  >
                    <Input.TextArea
                      value={editForm.description}
                      onChange={(e) => setEditForm({ ...editForm, description: e.target.value })}
                      placeholder="请输入组描述（可选）"
                      rows={3}
                      maxLength={500}
                      showCount
                    />
                  </Form.Item>

                  {editingGroup?.is_system && (
                    <div style={{
                      padding: '8px 12px',
                      backgroundColor: '#fff2f0',
                      border: '1px solid #ffccc7',
                      borderRadius: '6px',
                      marginBottom: '16px'
                    }}>
                      <Text type="warning" style={{ fontSize: '12px' }}>
                        ⚠️ 这是系统组，请谨慎修改
                      </Text>
                    </div>
                  )}
                </Form>
              ),
            },
            {
              key: 'users',
              label: (
                <span>
                  <UserOutlined />
                  用户管理 ({selectedUsers.length})
                </span>
              ),
              children: (
                <div style={{ marginTop: 16 }}>
                  <Transfer
                    dataSource={allUsers.map(user => ({
                      key: user.id.toString(), // 确保key是字符串
                      title: `${user.username} (${user.email})`,
                      description: user.is_active ? '激活' : '禁用',
                      disabled: !user.is_active
                    }))}
                    targetKeys={selectedUsers.map(id => id.toString())} // 确保targetKeys是字符串数组
                    onChange={(targetKeys, direction, moveKeys) => {
                      console.log('🔄 用户变更:', { targetKeys, direction, moveKeys });
                      const newSelectedUsers = targetKeys.map(key => parseInt(key.toString(), 10));
                      console.log('🎯 新选中用户:', newSelectedUsers);
                      setSelectedUsers(newSelectedUsers);
                    }}
                    render={item => item.title}
                    titles={['可选用户', '已选用户']}
                    showSearch
                    filterOption={(inputValue, option) =>
                      option.title.toLowerCase().includes(inputValue.toLowerCase())
                    }
                    listStyle={{
                      width: 350,
                      height: 400,
                    }}
                  />
                  <div style={{ marginTop: 8, color: '#666', fontSize: '12px' }}>
                    💡 提示：禁用的用户无法添加到组中
                  </div>
                </div>
              ),
            },
            {
              key: 'permissions',
              label: (
                <span>
                  <KeyOutlined />
                  权限管理 ({selectedPermissions.length})
                </span>
              ),
              children: (
                <div style={{ marginTop: 16 }}>
                  <Transfer
                    dataSource={allPermissions.map(permission => ({
                      key: permission.id.toString(),
                      title: permission.name,
                      description: `${permission.content_type_name} | ${permission.codename}`,
                    }))}
                    targetKeys={selectedPermissions.map(id => id.toString())}
                    onChange={(newTargetKeys, direction, moveKeys) => {
                      console.log('🔄 权限变更:', { newTargetKeys, direction, moveKeys });
                      const newSelectedPermissions = newTargetKeys.map(key => parseInt(key.toString(), 10));
                      console.log('🎯 新权限数组:', newSelectedPermissions);
                      setSelectedPermissions(newSelectedPermissions);
                    }}
                    render={item => (
                      <div>
                        <div>{item.title}</div>
                        <div style={{ fontSize: '11px', color: '#999' }}>{item.description}</div>
                      </div>
                    )}
                    titles={['可选权限', '已选权限']}
                    showSearch
                    filterOption={(inputValue, option) =>
                      option.title.toLowerCase().includes(inputValue.toLowerCase()) ||
                      option.description.toLowerCase().includes(inputValue.toLowerCase())
                    }
                    listStyle={{
                      width: 350,
                      height: 400,
                    }}
                  />
                  <div style={{ marginTop: 8, color: '#666', fontSize: '12px' }}>
                    💡 提示：可以按权限名称或代码名搜索
                  </div>
                </div>
              ),
            },
          ]}
        />
      </Modal>

      {/* 创建组Modal */}
      <Modal
        title="创建组"
        open={createVisible}
        onCancel={() => {
          setCreateVisible(false);
          createForm.resetFields();
        }}
        footer={null}
        width={500}
      >
        <ProForm
          form={createForm}
          onFinish={handleCreateGroup}
          submitter={{
            searchConfig: {
              submitText: '创建',
              resetText: '取消',
            },
            submitButtonProps: {
              loading: createLoading,
              icon: <PlusOutlined />,
            },
            resetButtonProps: {
              onClick: () => {
                setCreateVisible(false);
                createForm.resetFields();
              },
            },
          }}
        >
          <ProFormText
            name="name"
            label="组名"
            rules={[
              { required: true, message: '请输入组名' },
              { max: 150, message: '组名不能超过150个字符' },
            ]}
            tooltip="组名用于系统内部标识，创建后不可修改"
            placeholder="请输入组名，如：editors"
          />

          <ProFormText
            name="display_name"
            label="显示名称"
            rules={[
              { required: true, message: '请输入显示名称' },
              { max: 100, message: '显示名称不能超过100个字符' },
            ]}
            tooltip="显示名称用于界面展示"
            placeholder="请输入显示名称，如：编辑组"
          />

          <ProFormText
            name="description"
            label="描述"
            tooltip="可选，描述组的用途"
            placeholder="请输入组的描述信息"
          />
        </ProForm>
      </Modal>
    </PageContainer>
  );
};

export default GroupsNew;
